#!/bin/bash
# build_x264.sh - 编译 x264 为 Android armeabi-v7a 的动态库 (.so)
# 作者：Pengxh (修改版)
# 在 WSL 中运行：bash build_x264.sh

# ================== 配置区 ==================
NDK_DIR="/home/vm/android-ndk-r21d"
ANDROID_API=26
HOST="arm-linux-androideabi"

TOOLCHAIN_DIR="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64"
CC="$TOOLCHAIN_DIR/bin/armv7a-linux-androideabi$ANDROID_API-clang"
CXX="$TOOLCHAIN_DIR/bin/armv7a-linux-androideabi$ANDROID_API-clang++"
AR="$TOOLCHAIN_DIR/bin/llvm-ar"
STRIP="$TOOLCHAIN_DIR/bin/llvm-strip"
RANLIB="$TOOLCHAIN_DIR/bin/llvm-ranlib"
SYSROOT="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64/sysroot"

# 输出目录
PREFIX="$(pwd)/android/armeabi-v7a"
mkdir -p "$PREFIX"

CFLAGS="-fPIC -DANDROID -D__ANDROID_API__=$ANDROID_API"
CXXFLAGS="$CFLAGS"
LDFLAGS=""

# ============================================

echo "🧰 NDK 路径: $NDK_DIR"
echo "⚙️  编译器: $CC"
echo "📦 输出路径: $PREFIX"

# 检查编译器是否存在
if [ ! -f "$CC" ]; then
    echo "❌ 编译器不存在: $CC"
    echo "请检查："
    echo "  1. NDK 路径是否正确"
    echo "  2. 是否使用了 Linux 版 NDK（android-ndk-r21d-linux.zip）"
    echo "  3. NDK 版本是否支持 armeabi-v7a"
    exit 1
fi

echo "✅ 编译器存在"
"$CC" --version | head -n 1

# 检查 configure 脚本
if [ ! -f "./configure" ]; then
    echo "❌ 错误：找不到 x264 的 configure 脚本！"
    echo "💡 提示：请确保你在 x264 源码根目录，例如："
    echo "      git clone https://code.videolan.org/videolan/x264.git"
    exit 1
fi

# 清理旧构建
make clean 2>/dev/null || true

echo "🔧 正在配置 x264（生成动态库）..."

env \
    CC="$CC" \
    CXX="$CXX" \
    AR="$AR" \
    STRIP="$STRIP" \
    RANLIB="$RANLIB" \
    CFLAGS="$CFLAGS" \
    CXXFLAGS="$CXXFLAGS" \
    LDFLAGS="$LDFLAGS" \
    ./configure \
        --host=$HOST \
        --enable-shared \
        --enable-static \
        --enable-pic \
        --disable-cli \
        --disable-asm \
        --disable-thread \
        --disable-avs \
        --disable-swscale \
        --disable-lavf \
        --disable-opencl \
        --sysroot="$SYSROOT" \
        --prefix="$PREFIX" \
    && echo "✅ 配置完成" || { echo "❌ 配置失败！"; exit 1; }

echo "🛠 正在编译 x264..."
make -j$(nproc) || { echo "❌ 编译失败！"; exit 1; }

echo "📦 正在安装..."
make install || { echo "❌ 安装失败！"; exit 1; }

echo ""
echo "🎉 x264 动态库编译成功！"
echo ""
echo "✅ 生成的动态库："
echo "   $PREFIX/lib/libx264.so"
echo ""
echo "✅ 头文件："
echo "   $PREFIX/include/x264.h"
echo ""
echo "📌 提示：你可以将 libx264.so 添加到 Android 项目 jniLibs/armeabi-v7a/ 中"
echo ""